//
//  OrderListVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/6.
//  Copyright © 2020 cat. All rights reserved.
//

#import "OrderListVC.h"
#import "SPPageMenu.h"
#import "OrderListCell.h"
#import "OrderModel.h"
#import "OrderDetailVC.h"
#import "PayOrderView.h"
#import "PublishEvaluateVC.h"
#import "AppendEvaluateVC.h"
#import "BuyerRefundDetailVC.h"
@interface OrderListVC ()<SPPageMenuDelegate,UITableViewDataSource, UITableViewDelegate,orderCellBtnDelegate>
{
    int pageIndex;
}
@property(nonatomic, strong)NSArray *titles;
@property(nonatomic, strong)NSArray *typeArr;
@property (nonatomic, strong) SPPageMenu *pageMenu;
@property (nonatomic, strong)UITableView *orderTable;
@property(nonatomic, strong)NSString *orderType;

@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)NSArray *models;
@property (nonatomic, strong)PayOrderView *payView;

@end

@implementation OrderListVC

-(NSArray *)models{
    NSMutableArray *array = [NSMutableArray array];
    
    for (NSDictionary *dic in self.dataArr) {
        OrderModel *model = [OrderModel modelWithDictionary:dic];
        [array addObject:model];
    }
    _models = array;
    return _models;
}


-(void)requestOrderData{
    YBWeakSelf;
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.getGoodsOrderList"];
    
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"type":self.orderType,
                          @"p":@(pageIndex),
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };

    [WYNetworking postWithUrl:@"Buyer.getGoodsOrderList" Dic:dic Suc:^(int code, id info, NSString *msg) {
        [self.orderTable.mj_header endRefreshing];
        [self.orderTable.mj_footer endRefreshing];
        if (code ==0) {
            NSArray *infos = info;
            if (pageIndex == 1) {
                [self.dataArr removeAllObjects];

                if (infos.count < 1) {
                    [PublicView showImgNoData:self.orderTable name:@"shop_无数据" text:YZMsg(@"你还没有相关订单")];
                    [self.orderTable reloadData];
                    return ;
                }else{
                    [PublicView hiddenImgNoData:self.orderTable];
                }
                
            }
            [self.dataArr addObjectsFromArray:infos];
            [self.orderTable reloadData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [self.orderTable.mj_header endRefreshing];
            [self.orderTable.mj_footer endRefreshing];

     }];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    [self.orderTable.mj_header beginRefreshing];
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.titleL.text  = YZMsg(@"我的订单");
    self.view.backgroundColor = UIColor.whiteColor;
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    
    _titles = @[YZMsg(@"全部"),YZMsg(@"待付款"),YZMsg(@"待发货"),YZMsg(@"待收货"),YZMsg(@"待评价"),YZMsg(@"退款")];
    _typeArr = @[@"all",@"wait_payment",@"wait_shipment",@"wait_receive",@"wait_evaluate",@"refund"];
    self.orderType = _typeArr[self.selectIndex];
    pageIndex = 1;
    self.dataArr = [NSMutableArray array];
    
    
    _pageMenu = [SPPageMenu pageMenuWithFrame:CGRectMake(0, 64+statusbarHeight, _window_width, 40) trackerStyle:SPPageMenuTrackerStyleLineAttachment];
    _pageMenu.tracker.backgroundColor = Pink_Cor;
    [_pageMenu setItems:self.titles selectedItemIndex:self.selectIndex];
    _pageMenu.delegate = self;
    _pageMenu.backgroundColor = UIColor.whiteColor;
    _pageMenu.dividingLine.hidden = YES;
    _pageMenu.selectedItemTitleColor = [UIColor blackColor];
    _pageMenu.unSelectedItemTitleColor = [UIColor grayColor];
    _pageMenu.selectedItemTitleFont =  [UIFont systemFontOfSize:14];
    _pageMenu.unSelectedItemTitleFont = [UIFont systemFontOfSize:14];
    _pageMenu.permutationWay = SPPageMenuPermutationWayNotScrollEqualWidths;
    [self.view addSubview:_pageMenu];
    
    [self.view addSubview:self.orderTable];
    [self requestOrderData];
}
- (void)pageMenu:(SPPageMenu *)pageMenu itemSelectedAtIndex:(NSInteger)index {
    NSLog(@"sssssss::::%zd",index);
    pageIndex = 1;
    self.orderType = _typeArr[index];
    [self requestOrderData];
}
-(UITableView *)orderTable{
    if (!_orderTable) {
        _orderTable = [[UITableView alloc]initWithFrame:CGRectMake(0, self.pageMenu.bottom, _window_width, _window_height-64-statusbarHeight-40) style:UITableViewStylePlain];
        _orderTable.delegate = self;
        _orderTable.dataSource = self;
        _orderTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _orderTable.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            pageIndex = 1;
            [self requestOrderData];
        }];
        _orderTable.mj_footer = [MJRefreshBackFooter footerWithRefreshingBlock:^{
            pageIndex ++;
            [self requestOrderData];
        }];
        _orderTable.backgroundColor = UIColor.whiteColor;
    }
    return _orderTable;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.models.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderModel *modelsss =self.models[indexPath.row];
    if ([modelsss.status isEqual:@"1"]) {
        return 190;
    }else{
        return 230;
    }
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    OrderModel *models =self.models[indexPath.row];
    
    OrderListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderListCell"];
//['status']  订单状态  -1 已关闭  0 待付款 1 待发货 2 待收货 3 待评价 4 已评价 5 退款
//['is_append_evaluate']  订单是否可追加评价 1 可以  0  不可以
//['refund_status']  退款处理结果 -1 失败 0 处理中 1 成功
    if ([models.status isEqual:@"0"]) {
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:0];
        }
    }else if ([models.status isEqual:@"-1"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:5];
        }
    }else if ([models.status isEqual:@"1"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:1];
        }
    }else if ([models.status isEqual:@"2"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:2];
        }
    }else if ([models.status isEqual:@"3"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:3];
        }
    }else if ([models.status isEqual:@"4"] &&[models.is_append_evaluate isEqual:@"1"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:7];
        }

    }else if ([models.status isEqual:@"4"] &&[models.is_append_evaluate isEqual:@"0"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:8];
        }

    }else if ([models.status isEqual:@"5"] && ![models.refund_status isEqual:@"0"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:4];
        }
    }else if ([models.status isEqual:@"5"] && [models.refund_status isEqual:@"0"]){
        if (!cell) {
            cell = [[[NSBundle mainBundle]loadNibNamed:@"OrderListCell" owner:nil options:nil]objectAtIndex:6];
        }
    }
    cell.backgroundColor = UIColor.whiteColor;
    cell.delegate = self;
    cell.model = models;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    OrderModel *models =self.models[indexPath.row];
    if ([models.status isEqual:@"5"]) {
        BuyerRefundDetailVC *refund = [[BuyerRefundDetailVC alloc]init];
        refund.orderId = models.idStr;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:refund animated:YES];

    }else{
        OrderDetailVC *detail = [[OrderDetailVC alloc]init];
        detail.orderId =models.idStr;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:detail animated:YES];

    }
}

-(void)btnClickWithTitle:(NSString *)titls AndModel:(OrderModel *)models
{
    if ([titls isEqual:YZMsg(@"删除订单")]) {
        UIAlertController *deleteAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"确定删除订单?") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self deleteOrder:models];
        }];
        [deleteAlert addAction:cancle];
        [deleteAlert addAction:sureAction];
        [cancle setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
        [sureAction setValue:Pink_Cor forKey:@"titleTextColor"];

        [self presentViewController:deleteAlert animated:YES completion:nil];
    }else if ([titls isEqual:YZMsg(@"取消订单")]){
        UIAlertController *cancelAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"确定取消订单？") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self cancelOrder:models];
        }];
        [cancelAlert addAction:cancle];
        [cancelAlert addAction:sureAction];
        [cancle setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
        [sureAction setValue:Pink_Cor forKey:@"titleTextColor"];
        [self presentViewController:cancelAlert animated:YES completion:nil];

    }else if ([titls isEqual:YZMsg(@"付款")]){
        [self showPayView:models];
    }else if ([titls isEqual:YZMsg(@"查看物流")]){
        [self lookExpress:models];
    }else if ([titls isEqual:YZMsg(@"确认收货")]){
        UIAlertController *cancelAlert = [UIAlertController alertControllerWithTitle:YZMsg(@"确定已收到商品？") message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancle = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self receiveGoods:models];
        }];
        [cancelAlert addAction:cancle];
        [cancelAlert addAction:sureAction];
        [cancle setValue:[UIColor lightGrayColor] forKey:@"titleTextColor"];
        [sureAction setValue:Pink_Cor forKey:@"titleTextColor"];

        [self presentViewController:cancelAlert animated:YES completion:nil];

    }else if ([titls isEqual:YZMsg(@"评价")]){
        [self evaluate:models];
    }else if ([titls isEqual:YZMsg(@"追加评价")]){
        [self appendEvaluate:models];
    }else if ([titls isEqual:YZMsg(@"退款详情")]){
//        [self appendEvaluate:models];
        [self refundOrderDetail:models];
    }
    
}

#pragma mark------退款----------
-(void)refundOrderDetail:(OrderModel *)model{
    BuyerRefundDetailVC *refund = [[BuyerRefundDetailVC alloc]init];
    refund.orderId = model.idStr;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:refund animated:YES];

}

#pragma mark ---删除订单---------
-(void)deleteOrder:(OrderModel *)model{
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.delGoodsOrder"];
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":model.idStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    [WYNetworking postWithUrl:@"Buyer.delGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            pageIndex = 1;
            [self requestOrderData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}

#pragma mark-----取消订单--------
-(void)cancelOrder:(OrderModel *)model{
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.cancelGoodsOrder"];
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":model.idStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    [WYNetworking postWithUrl:@"Buyer.cancelGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            pageIndex = 1;
            [self requestOrderData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}

-(void)showPayView:(OrderModel *)model{
    YBWeakSelf;
    if (_payView) {
        [_payView removeFromSuperview];
        _payView = nil;
    }

    _payView = [[PayOrderView alloc]initWithPrice:model.price AndOrderId:model.idStr AndShopName:[model.shop_info valueForKey:@"name"]];
    _payView.frame = CGRectMake(0, 0, _window_width, _window_height);
    _payView.hideEvent = ^(BOOL paySuccess) {
        [weakSelf.payView removeFromSuperview];
        weakSelf.payView = nil;
        OrderDetailVC *detail = [[OrderDetailVC alloc]init];
        detail.orderId =model.idStr;
        [[YBBaseAppDelegate sharedAppDelegate]pushViewController:detail animated:YES];

    };
//    _payView.hideEvent = ^{
//        [weakSelf.payView removeFromSuperview];
//        weakSelf.payView = nil;
//    };
    [self.view addSubview:_payView];
}
#pragma mark-----查看物流--------
-(void)lookExpress:(OrderModel *)model{        
    NSString *url =[NSString stringWithFormat:@"%@/appapi/express/index",h5url];
    PubH5 *h5VC = [[PubH5 alloc]init];
    h5VC.url = [self addurl:url addModel:model];
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];

}
//所有h5需要拼接uid和token
-(NSString *)addurl:(NSString *)url addModel:(OrderModel *)models{
    return [url stringByAppendingFormat:@"&uid=%@&token=%@&orderid=%@&user_type=buyer",[Config getOwnID],[Config getOwnToken],models.idStr];
}
#pragma mark------确认收货-------
-(void)receiveGoods:(OrderModel *)model{
    NSString *url = [purl stringByAppendingFormat:@"?service=Buyer.receiveGoodsOrder"];
    NSDictionary *signdic = @{@"uid":[Config getOwnID],@"token":[Config getOwnToken], @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]]};
    NSString *sign = [PublicObj sortString:signdic];

    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"orderid":model.idStr,
                          @"time":[NSNumber numberWithLong: (long)[[NSDate date] timeIntervalSince1970]],
                          @"sign":sign
                          };
    
    [WYNetworking postWithUrl:@"Buyer.receiveGoodsOrder" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            [MBProgressHUD showError:msg];
            pageIndex = 1;
            [self requestOrderData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];
}
#pragma mark-----评价-------
-(void)evaluate:(OrderModel *)model{
    PublishEvaluateVC *evaluate = [[PublishEvaluateVC alloc]init];
    evaluate.model = model;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:evaluate animated:YES];
}
#pragma mark------追加评价-------
-(void)appendEvaluate:(OrderModel *)model{
    AppendEvaluateVC *append = [[AppendEvaluateVC alloc]init];
    append.model = model;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:append animated:YES];

}
@end
